package com.kompas.bola.application.fragment;

import java.util.ArrayList;
import java.util.List;

import com.google.analytics.tracking.android.Log;
import com.kompas.bola.application.DetailActivity;
import com.kompas.bola.application.R;
import com.kompas.bola.application.adapter.ListAdapter;
import com.kompas.bola.application.adapter.ListBookmarkAdapter;
import com.kompas.bola.application.dao.Dao;
import com.kompas.bola.application.db.CrudHelper;
import com.kompas.bola.application.model.Content;
import com.kompas.bola.application.ui.ListUI;
import com.kompas.bola.application.ui.ListUI.OnRefreshListener;
import com.kompas.bola.application.utils.Constants;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebSettings.ZoomDensity;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class BookmarkFragment extends Fragment {
	private ListUI list;
	private String _getPubDate;
	private ListBookmarkAdapter adapter;
	private AsyncTask<String, Void, List<Content>> updateTask;	
	private List<Content> list_data					= new ArrayList<Content>();
	private WebView imgProgressBar;
	private int page 								= 1;
	private int initialPage 						= 1;
	private ProgressDialog pDialog;
	/** ======================================================================= */
	public BookmarkFragment(){}
	/** =========================================================================== */
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);			
		
		View view									= inflater.inflate(R.layout.main, container, false);
		
		list										= (ListUI) view.findViewById(R.id.list);
		adapter										= new ListBookmarkAdapter(getActivity(), list_data);			

		imgProgressBar								= (WebView) view.findViewById(R.id.imgProgressBarMain);

		String path									= "file:///android_asset/loading.html";
		imgProgressBar.loadUrl(path);	
		imgProgressBar.getSettings().setDefaultZoom(ZoomDensity.FAR);
		imgProgressBar.setVisibility(View.VISIBLE);	

		/** 
		 * Load Content Detail Task */
		new LoadTask().execute();
				
		/**
		 * Pull Click Listener */		
		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				// TODO Auto-generated method stub
				String guid 						= ((TextView) view.findViewById(R.id.guid)).getText().toString();						
				Intent detail 						= new Intent(getActivity(),DetailActivity.class);
		    	
				detail.putExtra(Constants.GUID, guid);
				detail.putExtra(Constants.POSITION, position);
				detail.putExtra(Constants.DETAIL_PARAM, Constants.DETAIL_BOOKMARK);
				detail.putExtra(Constants.BOOKMARK, Constants.YES);
				startActivityForResult(detail, 0);
			}
		});
		
		
		/**
		 * Pull Refresh Listener */
		list.setOnRefreshListener(new OnRefreshListener() {			
			public void onRefresh() {
				// TODO Auto-generated method stub
				updateTask							= new AsyncTask<String, Void, List<Content>>(){
					
					@Override
					protected List<Content> doInBackground(String... params) {
						// TODO Auto-generated method stub
						try {
							list.prepareForRefresh();
			                Thread.sleep(3000);
			            } catch (InterruptedException e) {
				            return null;
			            }
			            return null;
					}
					
					protected void onPostExecute(
							List<Content> result){
						if (isCancelled())
							return;

						list.resetHeader();								
						list.onRefreshComplete();
					}					
				}.execute();
			}
		});
		
		return view;		
	}
	/** =========================================================================== */
	public class LoadTask extends AsyncTask<String, Void, List<Content>>{

		@Override
		protected List<Content> doInBackground(String... params) {
	    	CrudHelper db					= new CrudHelper(getActivity());
			
			List<Content> list_content		= new ArrayList<Content>();
			
			try {
				list_content				= db.getAllBookmark(page); // Sync Data
			} catch (Exception e) {
				// TODO Auto-generated catch block
				cancel(true);
				Log.e(Constants.ERROR+" Failed get bookmark !!!");
				Toast.makeText(getActivity(), Constants.EMPTY_DATA, Toast.LENGTH_LONG).show();
			}			
			return list_content;
		}	 

		protected void onPostExecute(
				List<Content> result){
			if (!isCancelled()){
				try {
					if(result.size() > 0){			
						list_data.addAll(result);

						if(list_data.get(0) != null){								
							list_data.get(0).setKEY_FIRST(true);
						}
						
						_getPubDate			= list_data.get(0).getKEY_PUB_DATE();
						
						try {
							adapter			= new ListBookmarkAdapter(getActivity(), list_data);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							cancel(true);
						}
						
						list.setAdapter(adapter);
						imgProgressBar.setVisibility(View.GONE);					
					}else{
						list_data.isEmpty();
						Toast.makeText(getActivity(), Constants.EMPTY_DATA, Toast.LENGTH_LONG).show();	
						imgProgressBar.setVisibility(View.GONE);				
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else
				return;		
		}
	}
	/** =========================================================================== */
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);

        inflater.inflate(R.menu.bookmark_menu, menu);
    }
	/** =========================================================================== */
	public void resetPage() {
		this.page 								= this.initialPage;
	}
	/** =========================================================================== */
	int isPage(){
		return this.page;
	}
	/** =========================================================================== */
    @Override
    public void onStop() {
        super.onStop();
		new LoadTask().cancel(true);
    }
	/** =========================================================================== */
}
